package com.ywger.service.server.impl;

import cn.hutool.core.collection.CollUtil;
import com.ywger.dao.entity.primary.EnsRegister;
import com.ywger.dao.entity.primary.TxInfo;
import com.ywger.dao.mapper.primary.EnsRegisterMapper;
import com.ywger.dao.mapper.primary.TxInfoMapper;
import com.ywger.service.constants.ChainState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tx.response.Callback;

import java.util.Date;
import java.util.List;

/**
 * @author chenmeng
 * @date 2021-11-14 14:21
 * @desc
 */
@Component
@Slf4j
public class EnsCommitCallback implements Callback {
    @Autowired
    TxInfoMapper txInfoMapper;

    @Autowired
    EnsRegisterMapper ensRegisterMapper;

    @Override
    public void accept(TransactionReceipt transactionReceipt) {
        String txHash = transactionReceipt.getTransactionHash();
        if(transactionReceipt.getStatus().equals("0x1")){
            updateDb(txHash,ChainState.SUCCESS);
        }
        if(transactionReceipt.getStatus().equals("0x0")){
            updateDb(txHash,ChainState.FAIL);
        }

    }

    @Override
    public void exception(Exception exception) {
        log.error("error:",exception);
    }


    private void updateDb(String txHash,ChainState chainState){
        List<TxInfo> txInfoList = txInfoMapper.selectByTxHash(txHash);
        if(CollUtil.isEmpty(txInfoList)){
            log.error("交易丢失：{}",txHash);
            return;
        }
        TxInfo txInfo = txInfoList.get(0);
        txInfo.setChainState(chainState.name());
        txInfo.setUpdateTime(new Date());
        txInfoMapper.updateByPrimaryKey(txInfo);

        List<EnsRegister> ensRegisterList = ensRegisterMapper.selectByEnsName(txInfo.getEnsName());
        if(CollUtil.isEmpty(ensRegisterList)){
            log.error("交易丢失：{},{}",txHash,txInfo.getEnsName());
            return;
        }
        EnsRegister ensRegister = ensRegisterList.get(0);
        ensRegister.setChainState(chainState.name());
        ensRegister.setUpdateTime(new Date());
        ensRegister.setCommitSuccessTime(new Date());
        ensRegisterMapper.updateByPrimaryKey(ensRegister);

    }
}
